package com.example.shuiyin.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@Slf4j
public class MybatisConfig {

    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        log.info("初始化DatabaseIdProvider...");
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("MySQL", "mysql");
        properties.setProperty("Oracle", "oracle");
        properties.setProperty("SQL Server", "sqlserver");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }
    
    @Bean
    public Object initDatabase(DataSource dataSource) {
        log.info("初始化数据库...");
        
        try {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            
            try {
                // 首先检查数据库连接是否正常
                Integer result = jdbcTemplate.queryForObject("SELECT 1", Integer.class);
                log.info("数据库连接测试: {}", result != null ? "成功" : "失败");
            } catch (Exception e) {
                log.error("数据库连接测试失败: {}", e.getMessage());
                return new Object(); // 如果连接测试失败，返回空对象，避免进一步操作
            }
            
            // 检查users表是否存在
            try {
                jdbcTemplate.queryForObject("SELECT 1 FROM users LIMIT 1", Integer.class);
                log.info("表 'users' 已存在");
            } catch (Exception e) {
                log.info("表 'users' 不存在，创建表...");
                
                try {
                    // 创建users表
                    jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS users (" +
                            "id BIGINT PRIMARY KEY AUTO_INCREMENT, " +
                            "username VARCHAR(50) NOT NULL UNIQUE, " +
                            "email VARCHAR(100) UNIQUE, " +
                            "phone VARCHAR(20) UNIQUE, " +
                            "password VARCHAR(100) NOT NULL, " +
                            "salt VARCHAR(50), " +
                            "avatar VARCHAR(200), " +
                            "nickname VARCHAR(50), " +
                            "role VARCHAR(20) DEFAULT 'USER', " +
                            "status VARCHAR(20) DEFAULT 'ACTIVE', " +
                            "user_level INT DEFAULT 1, " +
                            "openid VARCHAR(100) UNIQUE, " +
                            "reset_token VARCHAR(100), " +
                            "reset_token_expire_time DATETIME, " +
                            "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " +
                            "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" +
                            ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                    
                    log.info("表 'users' 创建成功");
                } catch (Exception tableCreateEx) {
                    log.error("表 'users' 创建失败: {}", tableCreateEx.getMessage());
                    return new Object();
                }
                
                try {
                    // 创建默认管理员账号
                    jdbcTemplate.update(
                            "INSERT INTO users (username, email, password, salt, nickname, role, status, user_level) " +
                                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                            "admin",
                            "admin@example.com",
                            // 密码: admin123 (实际项目中应使用BCrypt加密)
                            "$2a$10$ZiKDfAi9J9LkydwIGWYGTekGvKbfJMTp4YHXty5w3iWLR.3/DF83e", 
                            "salt123",
                            "系统管理员",
                            "ADMIN",
                            "ACTIVE",
                            10
                    );
                    log.info("默认管理员账号创建成功");
                } catch (Exception userCreateEx) {
                    log.error("默认管理员账号创建失败: {}", userCreateEx.getMessage());
                }
            }
            
        } catch (Exception e) {
            log.error("初始化数据库失败: {}", e.getMessage(), e);
        }
        
        log.info("数据库初始化流程完成");
        return new Object();
    }
} 